package com.fau.wmbj.server.service.impl;


import com.fau.wmbj.server.entity.SysConfig;
import com.fau.wmbj.server.service.SysConfigService;
import com.fau.wmbj.server.service.base.BaseServiceImpl;
import com.fau.wmbj.server.utils.Filter;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 系统配置
 *
 * @author jiawei
 * @version 1.0
 * @datetime 2023-03-21 16:57
 */
@Service("sysConfigService")
public class SysConfigServiceImpl extends BaseServiceImpl<SysConfig, Long> implements SysConfigService {

    @Override
    @Cacheable(value = "sysConfig", condition = "#useCache")
    public List<SysConfig> findAllConfig(boolean useCache) {
        return super.findAll();
    }

    @Override
    @Cacheable(value = "sysConfig", condition = "#useCache")
    public Map<String, Object> findAllConfigAsMap(boolean useCache) {
        List<SysConfig> allConfig = findAllConfig(useCache);
        Map<String, Object> map = new HashMap<>();
        for (SysConfig sysConfig : allConfig) {
            map.put(sysConfig.getConfigKey(), sysConfig.getConfigValue());
        }
        return map;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "sysConfig", allEntries = true)
    public SysConfig updateConfig(String configGroup, String configKey, String configValue) {
        SysConfig sysConfig = super.findEntity(Filter.eq("configKey", configKey));
        if (sysConfig != null) {
            sysConfig.setConfigValue(configValue);
            if (StringUtils.isNotBlank(configGroup)) {
                sysConfig.setConfigGroup(configGroup);
            }
            super.update(sysConfig);
        } else {
            sysConfig = new SysConfig();
            sysConfig.setConfigGroup(configGroup);
            sysConfig.setConfigKey(configKey);
            sysConfig.setConfigValue(configValue);
            return super.save(sysConfig);
        }
        return sysConfig;
    }

    @Override
    @Cacheable(value = "sysConfig")
    public String getConfigValue(String configKey) {
        SysConfig sysConfig = super.findEntity(Filter.eq("configKey", configKey));
        return sysConfig.getConfigValue();
    }

    @Override
    @Cacheable(value = "sysConfig")
    public List<SysConfig> getConfigByGroup(String configGroup) {
        return super.findList(Filter.eq("configGroup", configGroup));
    }

    @Override
    @Cacheable(value = "sysConfig")
    public SysConfig find(Long id) {
        return super.find(id);
    }


}
